package com.github.tommas.admintpl.common;

import com.github.tommas.admintpl.bean.vo.Pagination;
import com.github.tommas.admintpl.bean.vo.PaginationQuery;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.util.List;

public class PaginationData<T> {
    private List<T> data;
    private Pagination pagination;

    public List<T> getData() {
        return data;
    }

    public Pagination getPagination() {
        return pagination;
    }

    public static <T> PaginationData<T> createFromQuery(PaginationQuery<?> pq, QueryExecutor<T> executor) {
        return createFromQuery(pq.getPagination(), executor);
    }

    public static <T> PaginationData<T> createFromQuery(Pagination pagination, QueryExecutor<T> executor) {
        Page<T> page = null;
        try {
            if (pagination.getCurrent() == 0) {
                pagination.setCurrent(1);
            }
            if (pagination.getPageSize() == 0) {
                pagination.setPageSize(20);
            }

            page = PageHelper.startPage(pagination.getCurrent(), pagination.getPageSize(), true);
            List<T> data = executor.execute();

            pagination.setCurrent(page.getPageNum());
            pagination.setTotal(page.getTotal());

            PaginationData<T> pd = new PaginationData<>();
            pd.data = data;
            pd.pagination = pagination;

            return pd;
        } finally {
            if (page != null) {
                page.close();
            }
        }
    }

    @FunctionalInterface
    public interface QueryExecutor<T> {
        List<T> execute();
    }
}
